/*
此插件依赖于xlsx.full.min.js;需先引入
FileReader共有4种读取方法：
1.readAsArrayBuffer(file)：将文件读取为ArrayBuffer。
2.readAsBinaryString(file)：将文件读取为二进制字符串
3.readAsDataURL(file)：将文件读取为Data URL
4.readAsText(file, [encoding])：将文件读取为文本，encoding缺省值为'UTF-8'
*/

var wb;//读取完成的数据
var rABS = false; //是否将文件读取为二进制字符串
var data_json;//读取后转换的json串;
function importf_preview(obj,ades,select_data) {//导入
    if(!obj.files) {
        return;
    }

    var f = obj.files[0];
    var file_ext = get_file_ext(f.name);
    if(file_ext != 'xls' && file_ext != 'xlsx'){
        layer.msg("请上传正确的excel文件");return;
    }

    var select_html = '<select class="import_header_select" name="import_select" style="height: 45px;border: none;min-width: 120px">';
    select_html += '<option value="">请选择字段</option>';
    for (var i=0; i<select_data.length; i++){
        var must_html = '';
        if(select_data[i].ismust == 1){
            select_html += '<option value="'+select_data[i].field+'" type="'+select_data[i].type+'" style="color: red">*'+select_data[i].name+'</option>';
        }else{
            select_html += '<option value="'+select_data[i].field+'" type="'+select_data[i].type+'">&nbsp;&nbsp;'+select_data[i].name+'</option>';
        }

    }
    select_html += '</select>';

    var reader = new FileReader();
    reader.onload = function(e){
        var data = e.target.result;
        if(rABS){
            wb = XLSX.read(btoa(fixdata(data)),{//手动转化
                type:'base64'
            });
        }else{
            wb = XLSX.read(data,{
                type:'binary'
            });
        }

        //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
        //wb.Sheets[Sheet名]获取第一个Sheet的数据

        if(wb.SheetNames.length < 1){
            layer.msg("请上传正确的excel文件");return;
        }
        var sheetContent = '';
        for (var i=0; i<wb.SheetNames.length; i++ ){
            sheetContent += '<p data-id="'+i+'" class="import_chioce_sheet" style="cursor: pointer;font-size: 14px;">'+wb.SheetNames[i]+'</p>';
        }


        let _close_index = layer.open({
            title: '请选择要导入的Sheet工作表',
            content: sheetContent,
            area: ['60%', '60%'],
            btn: ['取消'],
            yes: function(index, layero) {
                layer.close(index);
            }
        });


        $(".import_chioce_sheet").click(function () {
            layer.close(_close_index);
            var sheetid = $(this).data('id')
            var data_json = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[sheetid]], {defval: '',range:'A1:AJ2000'});
            if(data_json != "" && data_json != null){
                if(data_json.length <1){
                    layer.msg("文件格式错误");return;
                }

                //去掉表头为空的列
                for(var key in data_json[0]){
                    if(key.indexOf('__EMPTY') != -1){
                        for (let i=0; i<data_json.length; i++){
                            delete data_json[i][key];
                        }
                    }
                }

                var max_tr_length = get_max_tr(data_json);

                //取表头
                $("#"+ades).empty();
                var tablehtml = "";
                tablehtml +='<p style="color: red">如数据有误，请单击表格修改</p>';
                tablehtml +='<table id="preview_table" style="width:100%;border: 1px solid #aaa;" border="1">';
                tablehtml +='<thead>';
                tablehtml +='<tr style="height:35px;">';
                tablehtml += '<th style="text-align: center;min-width: 40px"></th>';
                for(var i=1; i<=max_tr_length; i++){
                    tablehtml +='<th  key="'+i+'" style="text-align:center;height: 45px;">'+select_html+'</th>';
                }
                tablehtml +='</tr>';
                tablehtml +='</thead>';
                tablehtml +='<tbody>';

                tablehtml +='<tr style="height:35px;">';
                tablehtml += '<td style="text-align: center;">行号</td>';
                for(var key in data_json[0]){
                    // if(key.indexOf('__EMPTY') == -1){
                    //     tablehtml +='<td style="text-align: center">'+key+'</td>';
                    // }else{
                    //     tablehtml +='<td></td>';
                    // }
                    tablehtml +='<td style="text-align: center;">'+key+'</td>';
                }
                tablehtml +='</tr>';

                //获取内容
                for(var i = 0; i < data_json.length;i++){
                    tablehtml +='<tr style="height:35px;">';
                    var xuhao = i+1;
                    tablehtml += '<td style="text-align: center;">'+xuhao+'</td>';
                    var content_i = 1;
                    for(var key in data_json[i]){
                        tablehtml +='<td><input key="'+content_i+'" style="width: 100%;;text-align:center;height:35px;border:0;" type="text" value="'+data_json[i][key]+'"></td>';
                        content_i++;
                    }

                    tablehtml +='<td style="text-align:center;color: red;cursor:  pointer;padding:0 15px"><span class="delect_tr">删</span></td>';
                    tablehtml +='</tr>';
                }
                tablehtml +='</tbody>';
                tablehtml +='</table>';
                $("#"+ades).append(tablehtml);

                $(".delect_tr").click(function(){
                    $(this).parent().parent().remove();
                    var tr_obj = $("#preview_table>tbody>tr");
                    for(var i=0; i<tr_obj.length; i++){
                        var ii = i;
                        if(ii > 0){
                            $(tr_obj[i]).children('td:first-child').html(ii);
                        }
                    }
                })

                $(".import_header_select").change(function () {
                    var select_key = $(this).parent('th').attr('key');
                    var field_type = $(this).children('option:selected').attr('type');
                    if(field_type == 'date'){
                        if($(this).parent('th').children('button').length == 0){
                            $(this).parent('th').append('<button class="layui-btn zhuan_date" onclick="zhuan_date(\''+select_key+'\')">日期转换</button>');
                        }
                    }else{
                        if($(this).parent('th').children('button').length > 0){
                            $(this).parent('th').children('button').remove();
                        }
                    }



                });

                $("#preview_table tbody tr td:first-child").css('position','relative');
                $("#preview_table tbody tr td:first-child").css('width','40px');
                $("#preview_table tbody tr td:first-child").css('height','35px');
                $("#preview_table tbody tr td:first-child").css('line-height','35px');
                // $("#preview_table tbody tr td:first-child").css('left','100px');
                $("#preview_table tbody tr td:first-child").css('background-color','#248BFE');
                $("#preview_table tbody tr td:first-child").css('color','#fff');


            }else{
                layer.msg("文件格式错误");return;
            }
        });

    }





    if(rABS){
        reader.readAsArrayBuffer(f);
    }else{
        reader.readAsBinaryString(f);
    }
}



function import_onscroll() {
    var wleft = document.getElementById('import_con').scrollLeft;
    $("#preview_table tbody tr td:first-child").css('left',wleft+'px');
}


function zhuan_date(select_key){
    $("#preview_table input").each(function(index,element){
        if($(this).attr('key') == select_key){
            if($(this).val().length > 0 && $(this).val() != ''){
                $(this).val(formatDate($(this).val(), '-'));
            }
        }

    });
}




//获取文件后缀
function get_file_ext(filename) {
    var fileName = filename.lastIndexOf(".");//取到文件名开始到最后一个点的长度
    var fileNameLength = filename.length;//取到文件名长度
    var fileFormat = filename.substring(fileName + 1, fileNameLength);//截
    return fileFormat;
}


function fixdata(data) { //文件流转BinaryString
    var o = "",
        l = 0,
        w = 10240;
    for(; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
    o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
    return o;
}

function get_max_tr(data) {
    var length = 0;
    for (var i=0; i<data.length; i++){
        var tr_length = 0;
        for(var key in data[i]){
            tr_length++;
        }
        if(tr_length > length){
            length = tr_length;
        }
    }
    return length;
}

/**
 * 导入时   数字 转为日期格式
 * @param numb
 * @param format
 * @returns {string}
 */
function formatDate(numb, format){
    if(numb.length < 1){
        return '';
    }

    if(numb.indexOf("/") != -1){
        return numb.replace(/\//g, "-");
    }
    if(isNaN(numb) && !isNaN(Date.parse(numb))){
        return numb;
    }

    if(numb.indexOf("|") != -1){
        return numb;
    }


    var time = new Date((numb - 1) * 24 * 3600000)
    time.setYear(time.getFullYear() - 70)
    var year = time.getFullYear() + ''
    var month = time.getMonth() + 1 + ''
    var date = time.getDate() + ''
    // if (format && format.length === 1) {
    //     return year + format + month + format + date
    // }

    if(isNaN(year) || isNaN(month) || isNaN(date)){
        return '';
    }

    if(year > 2099){
        year = 2099;
    }
    if(year < 1970){
        year = 1970;
    }

    return year + format + (month < 10 ? '0' + month : month) + format  + (date < 10 ? '0' + date : date)
}
